<?php 
	
	
	set_include_path('/home/freshbuzzing/www/140dev/db');
	//set_include_path('/Library/WebServer/Documents/140dev/db');
	
	require_once('140dev_config.php');	  
	require_once('db_lib.php');

	//set_include_path('/Library/WebServer/Documents/log');
	set_include_path('/home/freshbuzzing/www/log');
	
	require_once('logging.php');
	
	$oDB = new db;
    
 	if(!$oDB)
  	{
  		die('Could not connect: ' . mysql_error());
  	}
	
	$logging = new Logging;
	$result_log = 'OK';
	$num_proceso = $logging->init_log("FACEBOOK - REGISTRO HIST");
	
	try{
	
		$result = $oDB->select('SELECT DS_USER_FB FROM MAST_FACEBOOK_ACCOUNTS WHERE BL_PARSE=1');
		
		$cont_reg = 0;
		while($row = mysqli_fetch_row($result))
		{
		  $request_url ="http://graph.facebook.com/" . $row[0];
		  $requests = file_get_contents($request_url);
		 
		  $fb_response = json_decode($requests,true);
	
		  $id = $fb_response['id'];		
		  $username = $fb_response['username'];
		  if(empty($username))
			  $username = $id;
		  $checkins = $fb_response['checkins'];
		  if(empty($checkins))
				$checkins = 0;
		  $price_range = $fb_response['price_range'];
		  $talking_about_count = $fb_response['talking_about_count'];
		  if(empty($talking_about_count))
			$talking_about_count=0;
		  $were_here_count = $fb_response['were_here_count'];
		  if(empty($were_here_count))
			$were_here_count=0;
		  $category = $fb_response['category'];	  
		  $link = $fb_response['link'];	  	  	  	  	  
		  $likes = $fb_response['likes'];	
		  if(empty($likes)) 
			$likes=0;
			
		  $oDB->update('MAST_FACEBOOK_ACCOUNTS', "DT_UPDATE=NOW(), NUM_CHECKIN = " . $checkins . ", DS_PRICE_RANGE= '" . $price_range . "', NUM_TALKING_ABOUT = " . $talking_about_count . ", NUM_WERE_HERE=" . $were_here_count . ", DS_CATEGORY='" . $category . "', DS_URL='" . $link . "', NUM_LIKES=" . $likes . ", ID_USER_FB='" . $id . "'", "DS_USER_FB = '" . $row[0] . "'");
		  $hoy = date("Y-m-d 00:00:00");
		  $oDB->insert('HIST_FACEBOOK_ACCOUNTS',"ID_USER_FB='".  $id . "', DT_TIMESTAMP='" . $hoy . "', NUM_LIKES=" . $likes);
		  
		  $cont_reg = $cont_reg + 1;	 
		}
		     	  
	}
	catch(Exception $e){
		$result_log = 'NOK';
		echo "Excepcion: "; 
		//printf($e->getMessage());
		//$logging->log_details($num_proceso,$e->getMessage());
	}	
	
	$logging->end_log($num_proceso, "Se han consultado " . $cont_reg . " paginas de Facebook de restaurantes",$result_log); 
	  	
	
?>